package com.yonyou.ucf.mdf.app.isvdxq.secondpart.service;

import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.ReRFIDCode;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.LocationEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.mapper.LocationMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.service.LocationEntityService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.EpcEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.StorerecordEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.TaglistEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.mapper.impl.EpclistMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.mapper.impl.StorerecordEntityMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.mapper.impl.TaglistMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.model.EpcBean;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.model.EpcEntityBean;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.model.EpcInParamBean;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TaglistService {
    @Autowired
    TaglistMapperImpl taglistMapper;
    @Autowired
    LocationEntityService locationService;
    @Autowired
    StorerecordService storerecordService;

    @Autowired
    TaglistMapperImpl tempTaglistMapper;

    @Autowired
    EpclistMapperImpl tempEpclistMapper;

    @Autowired
    StorerecordEntityMapperImpl tempStorerecordEntityMapper;

    public TaglistEntity SelectById(String id) {
        return taglistMapper.selectById(id);
    }

    public List<TaglistEntity> SelectByIds(List<String> ids) {
        return taglistMapper.selectByIds(ids);
    }

    public List<TaglistEntity> SelectAll(String tenantId) {
        return taglistMapper.selectAll(tenantId);
    }

    public Integer InsertEntity(TaglistEntity entity) {
        return taglistMapper.insert(entity);
    }

    public Integer UpdateEntity(TaglistEntity entity) {
        return taglistMapper.updateByPrimaryKey(entity);
    }

    public Integer DeleteById(Long id, String tenantId) {
        return taglistMapper.deleteByPrimaryKey(id, tenantId);
    }

    //根据托盘tag ids批量删除数据
    public Integer DeleteByIds(List<Long> ids, String tenant_id) {
        return taglistMapper.deleteByPrimaryKeys(ids, tenant_id);
    }

    public Integer DeleteByEpcs(List<String> ids, String tenant_id) {
        int rInt = taglistMapper.deleteByEpcKeys(ids, tenant_id);
        return rInt;
    }

    //托盘新增物料信息
    @Transactional(rollbackFor = Exception.class)
    public Integer AddEpcToTag(List<TaglistEntity> dataList, String tag, String tenant_id, String modifier) {
        if (dataList.size() == 0) return 0;
        //判断托盘如果有货位信息，则新增物料自动赋值货位信息
        List<EpcEntity> tempEntity = taglistMapper.selectEpcinfoByTag(tag, tenant_id);
        int rInt_tag = tempTaglistMapper.insertBatch(dataList);
        List<String> strList = dataList.stream().map(it -> it.getCoderfid()).distinct().collect(Collectors.toList());
        String locationId = "";
        if (tempEntity != null && tempEntity.size() > 0) {
            locationId = tempEntity.get(0).getLocation_id();
        }
        if (!StringUtils.isEmpty(locationId)) {
            String shelfId = tempEntity.get(0).getShelf_id();
            int rInt = tempTaglistMapper.EditCoderfid(strList, modifier, tenant_id, locationId, shelfId);
        }
        return rInt_tag;
    }

    //新增并更新
    public Integer InsertBatch(List<TaglistEntity> list) {
        if (list.size() == 0) return 0;
        long start = System.currentTimeMillis();
        int res = taglistMapper.insertBatch(list);
        long end = System.currentTimeMillis();
        System.out.println("---------------" + (start - end) + "---------------");
        return res;
    }

    //根据托盘查询物料标签
    public List<TaglistEntity> SelectByTag(String tag, String tenantId) {
        return taglistMapper.selectEntityByTag(tag, tenantId);
    }

    //根据托盘查询物料标签
    public List<EpcEntity> SelectInfoByTag(String tag, String tenantId) {
        return taglistMapper.selectInfoByTag(tag, tenantId);
    }

    /**
     * 返回EPC列表 epccode
     *
     * @param tag
     * @param tenantId
     * @return
     */
    public List<String> SelectEpcByTag(String tag, String tenantId) {
        List<String> result = new ArrayList<>();
        List<TaglistEntity> res = taglistMapper.selectEntityByTag(tag, tenantId);
        if (res == null || res.size() == 0) return result;
        result = res.stream().map(it -> it.getCoderfid()).distinct().collect(Collectors.toList());
        return result;
    }

    //返回EPC列表
    public EpcEntity SelectEpcEntityByTag(String tag, String tenantId) {
        List<TaglistEntity> res = taglistMapper.selectEntityByTag(tag, tenantId);
        if (res == null || res.size() == 0) return null;
        String epc = res.get(0).getCoderfid();
        return taglistMapper.selectEpcEntityByKey(epc, tenantId);
    }

    //根据EPC批量查询
    public List<TaglistEntity> SelectByEpcs(List<String> strList, String tenantId) {
        List<TaglistEntity> taglistEntities = new ArrayList<>();
        if (strList == null || strList.size() == 0) return taglistEntities;
        return taglistMapper.selectByEpcs(strList, tenantId);
    }

    //根据EPC ids获取信息
    public List<EpcEntity> SelectEpcInfoByIds(List<String> ids, String tenant_id) {
        List<EpcEntity> list_Epc = taglistMapper.selectInfoByEpcIds(ids, tenant_id);
        return list_Epc;
    }

    //根据EPC ids获取信息
    public EpcEntity SelectEpcEntityById(String id, String tenant_id) {
        return taglistMapper.selectEpcEntityById(id, tenant_id);
    }

    public List<EpcEntity> SelectEpcEntityByEpcs(List<String> strList, String tenant_id) {
        return taglistMapper.selectEpcEntityByEpcs(strList, tenant_id);
    }

    // 根据EPC 修改物料信息
    @Transactional(rollbackFor = Exception.class)
    public Integer RomoveByIds(List<String> strList, String tenant_id, String modifier, String tag) throws Exception {
        //修改托盘数据EPC
        List<TaglistEntity> tempList = SelectByEpcs(strList, tenant_id); //新旧所有数据
        List<TaglistEntity> dataList = TaglistService.CreateEntityByEpc(strList, tempList, tenant_id, modifier, modifier, tag, "");
        int rInt_tag = tempTaglistMapper.insertBatch(dataList);
        //Epc更新
        List<EpcEntity> epcEntities = tempEpclistMapper.selectByEpcs(strList, tenant_id);
        EpcEntity epcEntity = epcEntities.stream().filter(it -> !StringUtils.isEmpty(it.getLocation_id())).findFirst().orElse(null);
        if (epcEntity != null) {
            for (EpcEntity entity : epcEntities) {
                entity.setLocation_id(epcEntity.getLocation_id());
                entity.setShelf_id(epcEntity.getShelf_id());
                if (entity.getRfid_status() == 0) {
                    entity.setRfid_status(1);
                }
            }
            int i = tempEpclistMapper.editForShangjia(epcEntities, tenant_id);
        }
        return rInt_tag;
    }

    /**
     * 组装托盘实体数据
     *
     * @param strList
     * @param tempList
     * @param tenantId
     * @param operuserId
     * @param opername
     * @param tag
     * @param orgId
     * @return
     */
    public static List<TaglistEntity> CreateEntityByEpc(List<String> strList, List<TaglistEntity> tempList, String tenantId, String operuserId
            , String opername, String tag, String orgId) {
        List<TaglistEntity> dataList = new ArrayList<>();
        //数据组装
        for (String epc : strList) {
            TaglistEntity entity = tempList.stream().filter(it -> it.getCoderfid().equals(epc)).findAny().orElse(null);
            if (entity == null) {
                entity = new TaglistEntity();
                entity.setId(Long.parseLong(MyTool.getRandomId()));
                entity.setCreateTime(MyTool.GenerateTime());
                entity.setCreator(operuserId);
                entity.setCreatorname(opername);
                entity.setYtenant_id(tenantId);
                entity.setVersion(2);
            }
            entity.setOpertime(MyTool.GenerateTime());
            entity.setOpername(opername);
            entity.setOperuserid(operuserId);
            entity.setStatus(0);
            entity.setOrgid(orgId);
            entity.setCoderfid(epc);
            entity.setName(tag);
            dataList.add(entity);
        }
        return dataList;
    }

    public static List<TaglistEntity> CreateNewEntityByEpc(List<String> strList, List<TaglistEntity> tempList, String tenantId, String operuserId
            , String opername, String tag, String orgId) {
        List<TaglistEntity> dataList = new ArrayList<>();
        //数据组装
        for (String epc : strList) {
            TaglistEntity entity = tempList.stream().filter(it -> it.getCoderfid().equals(epc)).findAny().orElse(null);
            if (entity == null) {
                entity = new TaglistEntity();
                entity.setId(Long.parseLong(MyTool.getRandomId()));
                entity.setCreateTime(MyTool.GenerateTime());
                entity.setCreator(operuserId);
                entity.setCreatorname(opername);
                entity.setYtenant_id(tenantId);
                entity.setVersion(2);
                entity.setStatus(0);
                entity.setOrgid(orgId);
                entity.setCoderfid(epc);
                entity.setName(tag);
                dataList.add(entity);
            }
        }
        return dataList;
    }

    // 根据EPC ids获取物料信息
    public List<EpcEntityBean> SelectInfoByEpcs(List<String> strList, String tenantId) {
        List<EpcEntityBean> res = new ArrayList<>();
        List<EpcEntity> resList = SelectEpcEntityByEpcs(strList, tenantId);
        if (resList.size() == 0) return res;
        List<String> ids_warehouse = resList.stream().map(it -> it.getWarehouse_id()).distinct()
                .collect(Collectors.toList());
        if (ids_warehouse.size() == 0) return res;
        List<LocationEntity> list_Location = locationService.getLocationByWhIds(ids_warehouse, tenantId);

        for (EpcEntity item : resList) {
            EpcEntityBean entity = MyTool.convertBean2Bean(item, EpcEntityBean.class);
            String locationId = entity.getLocation_id();
            if (list_Location.size() > 0) {
                String warehouseName = list_Location.get(0).getWarehouse_name();
                String warehouseCode = list_Location.get(0).getWarehouse_code();
                entity.setWarehouseName(warehouseName);
                entity.setWarehouseCode(warehouseCode);
                entity.setWarehouse_code(warehouseCode);
            }
            // 补全货位信息
            if (!StringUtils.isEmpty(locationId)) {
                LocationEntity locationEntity = list_Location.stream()
                        .filter(it -> it.getId().equals(locationId))
                        .findFirst().orElse(null);

                String locationName = GetFullPathnameByEntity(locationEntity, list_Location);
                entity.setLocationName(locationName);
                entity.setPath(locationEntity.getPath());
            }

            res.add(entity);
        }
        return res;
    }

    /**
     * EPC复核配货 自动检测是否完成，并更新单据状态
     *
     * @param strList
     * @param modifier
     * @param tenant_id
     * @param status
     * @return
     */
    public Integer EditEpcListStatus(List<String> strList, String modifier, String tenant_id, int status) {
        int rInt = taglistMapper.editEpcListStatus(strList, modifier, tenant_id, status);
        return rInt;
    }

    //V1升级
    public Integer EditEpclist(EpcInParamBean paramBean, List<String> strList, String modifier, String tenant_id) {
        return taglistMapper.editEpcList(paramBean, strList, modifier, tenant_id);
    }

    //批量物料下架 多标签同货位
    public Integer CleanEpclist(List<String> strList, String modifier, String tenant_id) {
        return taglistMapper.cleanCoderfid(strList, modifier, tenant_id);
    }



    //多标签
    public Integer EditEpclistBatch(EpcInParamBean paramBean, String modifier, String tenant_id) {
        int rInt = taglistMapper.editEpcListBatch(paramBean, modifier, tenant_id);
        return rInt;
    }

    /**
     * 批量解绑EPC接口 标签释放
     *
     * @param EpcIds
     * @param ordertype
     * @param userId
     * @param tenant_id
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer EditEpclistDestory(List<String> EpcIds, String ordertype, String userId, String tenant_id) throws Exception {
        //删除Tag托盘绑定记录EPCs
        List<EpcEntity> list_Epc = taglistMapper.selectInfoByEpcIds(EpcIds, tenant_id);
        if (list_Epc.size() == 0) {
            return 0;
        }
        //软删除绑定记录
        int rInt_record = tempStorerecordEntityMapper.deleteStorerecord(EpcIds, ordertype, userId, tenant_id);
        //删除物资标签 ids
        if (list_Epc.size() > 0) {
            for (EpcEntity item : list_Epc) {
                item.setPk_temp("bindepcdel");
            }
            tempEpclistMapper.insertBatchHistory(list_Epc);
            int rInt = tempEpclistMapper.deleteByIds(EpcIds, tenant_id);
            List<String> epcs = list_Epc.stream().map(it -> it.getRfid_code()).distinct().collect(Collectors.toList());
            int rInt_tag = tempTaglistMapper.deleteByEpcKeys(epcs, tenant_id);
        }
        return rInt_record;
    }

    //检查是否可以销毁 epc id
    public boolean CheckEpcDestory(List<String> strList, String ordertype, String tenantId) {
        boolean res = true;
        List<StorerecordEntity> list = storerecordService.selectStorerecordByEpcIds(strList, ordertype, tenantId);
        if (list.size() == 0) return res;
        // 分配标签 同步用友后回写 用于判断不能撤销绑定
        for (StorerecordEntity temp : list) {
            if (!StringUtils.isEmpty(temp.getBatch_no())) {
                res = false;
                break;
            }
        }
        return res;
    }

    @Autowired
    LocationMapperImpl locationMapper;

    //拣货货位提示接口
    public List<EpcBean> GetEpctiplist(List<String> proids, List<String> localtionIds,
                                       String batchno, String tenantId) throws Exception {
        List<EpcBean> datalist = taglistMapper.selectEpcinfoTip(proids, localtionIds, batchno, tenantId);
        //补全货位信息
        List<String> ids = new ArrayList<>();
        for (EpcBean item : datalist) {
            if (!StringUtils.isEmpty(item.getPath())) {
                ids.addAll(Arrays.asList(item.getPath().split("\\|")));
            }
        }
        ids = ids.stream().distinct().collect(Collectors.toList());
        if (ids.size() > 0) {
            List<LocationEntity> tempList = locationMapper.selectLocationByIds(ids, tenantId);
            for (EpcBean item : datalist) {
                if (StringUtils.isEmpty(item.getPath())) continue;
                String locationName = GetLocationName(tempList, item.getPath());
                item.setLocationName(locationName);
            }
        }
        return datalist;
    }

    //复核接口（按单复核、托盘）
    public List<EpcBean> GetEpcinfolist(String orderid, String ordertype, String tag, String tenantId,
                                        List<String> localtionIds) throws Exception {
        List<EpcBean> datalist = new ArrayList<>();
        List<String> ids_epc = new ArrayList<>();
        List<StorerecordEntity> storerecordEntities = storerecordService.SelectEntityList(orderid, ordertype, tenantId);
        if (storerecordEntities != null && storerecordEntities.size() > 0) {
            ids_epc = storerecordEntities.stream().map(it -> it.getRfidcodeId()).distinct()
                    .collect(Collectors.toList());
        }
        if (ids_epc.size() > 0) {
            List<EpcEntityBean> epclist = taglistMapper.getEpcinfo(ids_epc, tenantId);
            for (EpcEntityBean entity : epclist) {
                StorerecordEntity tempStorerecordEntity = storerecordEntities.stream()
                        .filter(it -> it.getRfidcodeId().equals(entity.getId()))
                        .findFirst().orElse(null);
                EpcBean modelEntity = MyTool.convertBean2Bean(entity, EpcBean.class);
                if (tempStorerecordEntity != null) {
                    modelEntity.setBatch_no(tempStorerecordEntity.getBatch_no());
                    modelEntity.setOrderid(tempStorerecordEntity.getOrderid());
                    modelEntity.setOrderdetailid(tempStorerecordEntity.getOrderdetailid());
                    modelEntity.setStorerecordid(tempStorerecordEntity.getId());
                }
                datalist.add(modelEntity);
            }
        }
        if (!StringUtils.isEmpty(tag)) {
            datalist = datalist.stream().filter(it -> it.getTag() != null && it.getTag().equals(tag)).collect(Collectors.toList());
        }
        if (localtionIds != null && localtionIds.size() > 0) {
            datalist = datalist.stream()
                    .filter(it -> localtionIds.contains(it.getLocation_id())).collect(Collectors.toList());
        }

        //补全货位信息
        List<String> ids = new ArrayList<>();
        for (EpcBean item : datalist) {
            if (!StringUtils.isEmpty(item.getPath())) {
                ids.addAll(Arrays.asList(item.getPath().split("\\|")));
            }
        }
        ids = ids.stream().distinct().collect(Collectors.toList());
        if (ids.size() > 0) {
            List<LocationEntity> tempList = locationMapper.selectLocationByIds(ids, tenantId);
            for (EpcBean item : datalist) {
                if (StringUtils.isEmpty(item.getPath())) continue;
                String locationName = GetLocationName(tempList, item.getPath());
                item.setLocationName(locationName);
            }
        }
        return datalist;
    }

    /**
     * 循环获取货位路径名称
     *
     * @param tempList
     * @param path
     * @return
     */
    public static String GetLocationName(List<LocationEntity> tempList, String path) {
        String res = "";
        List<String> ids = Arrays.asList(path.split("\\|"));
        for (String id : ids) {
            LocationEntity entity =
                    tempList.stream().filter(it -> it.getId().equals(id)).findFirst().orElse(null);
            if (entity != null) {
                res += entity.getLocationName() + " ";
            }
        }
        return res;
    }

    /**
     * 获取货位全路径名称
     * path 字段解析
     *
     * @param locationEntity
     * @param list_Location
     * @return
     */
    public static String GetFullPathnameByEntity(LocationEntity locationEntity, List<LocationEntity> list_Location) {
        String path = "";
        List<String> tempIds = new ArrayList<>();
        if (locationEntity != null) {
            tempIds.add(locationEntity.getWarehouse_id());
            String[] _ids = locationEntity.getPath().split("\\|");
            tempIds.addAll(Arrays.asList(_ids));
            tempIds = tempIds.stream().distinct().collect(Collectors.toList());
            path = String.join("|", tempIds);
        }

        String locationName = GetLocationName(list_Location, path);
        return locationName;
    }

    /**
     * 获取指定范围 货位Ids
     *
     * @param key
     * @param tenantId
     * @return
     */
    public List<String> GetLocationListByPath(String key, String tenantId) {
        String locationID = "%" + key + "%";
        List<LocationEntity> tempList = locationMapper.GetLocationListByPath(locationID, tenantId);
        return tempList.stream().filter(it -> it.getIsEnd() == true).map(it -> it.getId()).collect(Collectors.toList());
    }

    // 待发货详情
    public List<ReRFIDCode> GetAllotDetail(String orderid, String pickbatchno, String tenant_id) {
        return taglistMapper.getAllotDetail(orderid, pickbatchno, tenant_id);
    }

    public List<TaglistEntity> SelectPage(String tenantId, int m, int n) {
        return taglistMapper.selectPage(tenantId, m, n);
    }

}
